package com.cbnu.SmartCampusLife;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

@SuppressLint({ "HandlerLeak", "WorldReadableFiles", "SetJavaScriptEnabled" })
public class BeforeMainMenu extends Activity {
    /** Called when the activity is first created. */
	String s[] = new String[4];
	Handler handler = new Handler()	{
		@Override
		public void handleMessage(android.os.Message msg) {
			if(s[0] != null) {
				Log.d("MSG", "Login Success!");
				Toast.makeText(BeforeMainMenu.this, "로그인 성공.", Toast.LENGTH_LONG).show();
				Intent intent = new Intent(BeforeMainMenu.this, MainMenu.class);
				intent.putExtra("loginChk", true);
		    	startActivity(intent);
		    	finish();
			}
			else {
				Log.d("MSG","Login Fail!");
				Toast.makeText(BeforeMainMenu.this, "로그인 실패. 다시 로그인하세요.", Toast.LENGTH_LONG).show();
				Intent intent = new Intent(BeforeMainMenu.this, SmartCampusLifeActivity.class);
				intent.putExtra("loginChk", false);
		    	startActivity(intent);
		    	finish();
			}
		};
	};	
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_before_main_menu);
        
        for (int i = 0; i < 3; i++) s[i] = null;
        
        class MyJavaScriptInterface{
    		@SuppressWarnings("unused")
			public void showHTML(String html){
    			FileOutputStream fos;
    			try {
    				fos = openFileOutput("logininfo.txt", Context.MODE_WORLD_READABLE);
    				fos.write(html.getBytes("UTF-8"));
    				fos.close();
    			} catch (Exception e) {
    				e.printStackTrace();
    			}
    			try {
    				FileInputStream fis = openFileInput("logininfo.txt");
    				BufferedInputStream bis = new BufferedInputStream(fis);
    				BufferedReader dis = new BufferedReader(new InputStreamReader(bis));
					int i = 0;
    				String str;
					do {
    					str = dis.readLine();
    					if(str.matches("(?i).*"+ "<td class=\"x1\">" + ".*")) {
    						s[i] = str.replace("</td>", "");
    						s[i] = s[i].replace("&nbsp;", " ");
    						s[i] = s[i].substring(46);
    						Log.d("Student Information", s[i]);
    						i++;
    					}
    				} while( !(str.equals("null")));
    				dis.close();
    				fis.close();
    			} catch(Exception e) {;}
    			try {
    				FileOutputStream fos1 = openFileOutput("stu_id.txt", Context.MODE_WORLD_READABLE);
					fos1.write(s[0].getBytes("UTF-8"));
					fos1.close();
					//If student are admitted before 2009-year, then use old building name, else use new building name
    			} catch(Exception e) {;}
    			try {
    				FileOutputStream fos1 = openFileOutput("stu_name.txt", Context.MODE_WORLD_READABLE);
					fos1.write(s[1].getBytes("UTF-8"));
					fos1.close();
    			} catch(Exception e) {;}
    			try {
    				FileOutputStream fos1 = openFileOutput("stu_part.txt", Context.MODE_WORLD_READABLE);
					fos1.write(s[2].getBytes("UTF-8"));
					fos1.close();
    			} catch(Exception e) {;}
    			try {
    				FileOutputStream fos1 = openFileOutput("stu_state.txt", Context.MODE_WORLD_READABLE);
					fos1.write(s[3].getBytes());
					fos1.close();
    			} catch(Exception e) {;}
    			Thread background = new Thread(new Runnable() {
					public void run() {
						try {
								handler.sendMessage(handler.obtainMessage());
						} catch (Throwable t) {;}
					}
				});
				background.start();
    		}
    	}
    	
    	WebView webview = (WebView)findViewById(R.id.bm_webView);
    	webview.getSettings().setJavaScriptEnabled(true);
    	webview.getSettings().setBuiltInZoomControls(true);
    	webview.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
        webview.setWebViewClient(new WebViewClient(){   //현재의 엑티비티 내에서 url을 보여주고자 할 경우 설정.
            @Override
    		public void onPageFinished(WebView view, String url) {
    			super.onPageFinished(view, url);
    			try {
    				view.loadUrl("javascript:window.HTMLOUT.showHTML('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");
    			} catch (Exception e) {
    				e.printStackTrace();
    			}
            }
        });
        webview.loadUrl("http://gaesin.chungbuk.ac.kr/jsp/loginInfo.jsp?menu=S");
    }
}